import { _ } from 'meteor/underscore';
import { msg } from '../notice/notice';
import { JoinClient } from 'meteor-publish-join';
import { Friends } from '/imports/models/Friends';
import { isMember } from '/imports/models/ChannelMembers';

Template.invite_member_modal.onCreated(function () {
  this.query = new ReactiveVar({});
  this.limit = new ReactiveVar(15);
  this.search = new ReactiveVar('');

  this.autorun(() => {
    this.query.set({
      user_id: Meteor.userId(),
      'info.username': {
        $regex: new RegExp(this.search.get())
      }
    });
    this.resultsSub = this.subscribe('get.friends', { user_id: Meteor.userId() }, this.limit.get());
    this.total = JoinClient.get('get.friends.counts');
  });
});

Template.invite_member_modal.onRendered(function () {
  const ps = new PerfectScrollbar('#invite-member-modal-body');

  $('#invite-member-modal-body').on('ps-y-reach-end', _.throttle(() => {
    let lmt = this.limit.get();
    if (this.total >= lmt) {
      this.limit.set(lmt + 15);
    }
  }, 200));
});

Template.invite_member_modal.helpers({
  results: function () {
    return Friends.find(Template.instance().query.get(), {
      limit: Template.instance().limit.get()
    });
  },

  loading: function () {
    return !Template.instance().resultsSub.ready();
  }
});

Template.invite_member_modal.events({
  'input #invite-member-input' (e, instance) {
    let text = $.trim(e.target.value);
    instance.search.set(text);
  },

});

Template.invite_member_item.helpers({
  display: function () {
    const user = Template.instance().data.result.info;
    if (user.profile.name) {
      return user.profile.name;
    } 
    return user.username;
  },

  username: function () {
    return Template.instance().data.result.info.username
  },

  avatar: function () {
    return Template.instance().data.result.info.profile.avatar;
  },

  isOwner: function () {
    if (Template.instance().data.channel) {
      return Template.instance().data.result.info._id === Template.instance().data.channel.owner.id;
    }
  },

  isMember: function () {
    if (Template.instance().data.channel) {
      return isMember(Template.instance().data.channel._id, Template.instance().data.result.friend_id);
    }
  }
});

Template.invite_member_item.events({
  'click .send-invite' (e, instance) {
    e.preventDefault();
    const options = {
      id: instance.data.channel._id,
      channelId: instance.data.channel.channelId,
      friendId: instance.data.result.friend_id
    };

    Meteor.call('inviteMember', options, (err, res) => {
      if (res) {
        $(e.currentTarget).addClass('d-none');
        msg({content: '邀请已发送'});
      }
    });
  }
});
